import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView
  },
  {
    path: '/about',
    name: 'about',
    // 路由的懒加载
    component: () => import('../views/AboutView.vue')
  },
  {
    path: '/user',
    component: () => import('../views/User.vue'),
    children: [
      {
        path: 'login',
        component: () => import('../views/Login.vue')
      },
      {
        path: 'register/:name/:age/:sex',
        component: () => import('../views/Register.vue')
      }
    ]
  },
  { 
    path: '/tieba',
    component: () => import('../views/TieBa.vue')
  },
  {
    path: '*',
    redirect: '/'
  }
]

// 创建路由实例
const router = new VueRouter({
  routes,
  mode: 'history'
})

// 路由前置守卫
router.beforeEach((to, from, next) => {
  if(to.path=='/' || to.path=='/user/login' || to.path.startsWith('/user/register')){
    return next() // 放行
  }
  if(localStorage.getItem('userInfo')){
    return next()
  }
  // 如果没有登录
  next('/user/login')
})

export default router
